package mk.edu.ii.navigatemacedonia;


import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.app.Activity;
import android.app.ProgressDialog;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;

import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginView  extends Activity{
	public static String LOG_KEY_PREFERENCE = "log_key_preference";
	public static String KEY = "key";
	ProgressDialog myProgressDialog = null;
	Handler handler = new Handler();
	@Override
    public void onCreate(Bundle savedInstanceState) {
			
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.login_view);
        
        final Button loginButton = (Button)findViewById(R.id.LoginButton);
        
        loginButton.setOnClickListener(new Button.OnClickListener() {
			
			public void onClick(View v) {
				myProgressDialog = ProgressDialog.show(LoginView.this,
		                "Please wait...", "Try to authenticate to server...", true);
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						String key = login();
						if(key != null){
							SharedPreferences pref = getSharedPreferences(LOG_KEY_PREFERENCE, Activity.MODE_PRIVATE);
							Editor editor = pref.edit();
							editor.putString(KEY, key);
							
							editor.commit();
							
							switchToMainView();
						}				
						myProgressDialog.dismiss();
					}
				}).start();
			}
		});
        
        final TextView registrationTextView = (TextView)findViewById(R.id.registration_link);
        registrationTextView.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				Intent i = new Intent(Intent.ACTION_VIEW);
				i.setData(Uri.parse(ServiceURL.URL+"SignUpMobile.aspx"));
				startActivity(i);
			}
		});
	}
	
	private String login(){
		EditText username = (EditText)findViewById(R.id.UserNameEditField);
		EditText password = (EditText)findViewById(R.id.PasswordEditField);
		Log.i("username:", username.getText().toString());
		Log.i("password:", password.getText().toString());
		
		return ServiceConnect.getInstance(getApplicationContext(), handler).login(username.getText().toString(),password.getText().toString());
	}
	
	private void switchToMainView(){
		Intent startIntent = new Intent(getApplicationContext(),NavigateMacedonia.class);
		startActivity(startIntent);
		finish();
	}

}
